package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.FileItem;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayMerchantItemFileUploadRequest;
import com.alipay.api.request.AlipayMerchantOrderSyncRequest;
import com.alipay.api.request.AlipayTradeOrderinfoSyncRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayMerchantItemFileUploadResponse;
import com.alipay.api.response.AlipayMerchantOrderSyncResponse;
import com.alipay.api.response.AlipayTradeOrderinfoSyncResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.google.common.collect.Lists;
import com.ytjj.common.constants.AlipayConstants;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.*;
import com.ytjj.qmyx.mall.constants.PayModeConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.*;
import com.ytjj.qmyx.mall.mapper.GroupBuyUserRelMapper;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.mapper.PayConfigDao;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.ProductSpec;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.ProductSpecResponse;
import com.ytjj.qmyx.mall.service.*;
import com.ytjj.qmyx.mall.utils.AlipayFactoryUtils;
import com.ytjj.qmyx.mall.utils.Base64Util;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.model.UsersDto;
import joptsimple.internal.Strings;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 普通创建订单的方式
 *
 *
 * @version 1.0
 *
 */
@Service("NORMAL")
@Slf4j
@RefreshScope
public class OrdersNormalServiceImpl implements CreateOrderService<CreateOrderRequest> {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductMapper productMapper;

    @Autowired
    private YxProductGroupBuyInfoService yxProductGroupBuyInfoService;
    @Autowired
    private YxGroupBuyInfoService yxGroupBuyInfoService;
    @Autowired
    private YxGroupBuyUserRelService yxGroupBuyUserRelService;
    @Resource
    private GroupBuyUserRelMapper groupBuyUserRelMapper;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;
    @Resource
    private RedissonClient redissonClient;
    @Value("${check.product.status:1}")
    private String checkProductStatus;//是否校验商品状态 1-校验  0-不需要校验
    @Resource
    private AlipayService alipayService;
    @Resource
    private UsersClient usersClient;
    @Resource
    private PayConfigDao payConfigDao;
    @Resource
    private AlipayFactoryUtils alipayFactory;
    @Resource
    private AlipayConstants alipayConstants;
    @Resource
    private RedisService redisService;

    @Override
    @Transactional
    public Integer createOrder(CreateOrderRequest request) {
        RLock lock = null;
        // 普通商品创建订单
        ProductSpec productSpec = productService.getProductSpecById(request.getProductSpecId());
        Product product = productMapper.selectByPrimaryKey(productSpec.getProductId());
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));
        if (checkProductStatus.equals("1")) {
            if (ProductStatusEnums.UP.getValue() != product.getStatus()) {
                throw new ApiException("商品已下架");
            }
        }
        log.info("====request.getFlag()==={},{}", request.getFlag(), product.getActivityType());
        Integer isDirectBuy = 0;
        // 支付方式为 “直接购买” 则取出现价字段
        if(PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag())){
            productSpec.setPrice(productSpec.getCurPrice());
            isDirectBuy = 1;
        }
        log.info("===productSpec==={}", productSpec);
        String orderParentNo = OrderUtils.getOrderCode(request.getUserId());//组合订单号
        //乘商品数量
        BigDecimal originalPrice_new = productSpec.getOriginalPrice();
        BigDecimal price_new = productSpec.getPrice();
        if (null != request.getProductSum() && request.getProductSum() > 1){
            originalPrice_new = productSpec.getOriginalPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
            price_new = productSpec.getPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
        }
        // 主订单
        Orders orders = ordersService.saveOrders(request.getUserId(), request.getTel(),originalPrice_new, price_new, request.getOrderSource(), request.getChannel(),null,request.getDynamicId(),orderParentNo,request.getAccount());
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                productSpec.getPrice(), productSpec.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(), productSpec.getId(),
                product.getActivityType(), null, product.getActivityMax(), product.getActivityMin(), product.getDescr(),isDirectBuy,request.getPageSourceV2(),
                null,product.getProductType(),0, productSpec.getCostPrice(), productSpec.getThreeSkuId(),request.getProductSum(),"",request.getScene());
        try {
            // 记录订单规格信息
            ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
            ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
            if (null != lock) {
                lock.unlock();
            }
        }catch (Exception e){
            log.error("发送到rabbitmq错误",e);
            if (null != lock) {
                lock.unlock();
            }
        }

        try{
//            String sourcePlatform = TokenUtil.getSourcePlatform();
//            if (StringUtils.isNotBlank(sourcePlatform) && "zfb".equals(sourcePlatform.toLowerCase())) {
//                UsersDto usersInfo = usersClient.getUsersInfo(request.getUserId());
//                if (usersInfo.getAlipayUserId() == null) {
//                    throw new ApiException("下单失败，支付宝用户id缺失");
//                }
//                alipayService.syncAliPayOrder("CREATE", orders.getOrderNo(), String.valueOf(orders.getId()), request.getUserId(), ordersInfo.getProductName(),orders.getCreateTime(),request.getChildId(),ordersInfo.getProductImg());
//
//            }
        }catch (Exception e) {
            log.error("同步支付宝订单状态失败CREATE-->到支付宝失败:{}",e.getMessage());
        }
        return orders.getId();
    }




    @Override
    public Integer cartCreateOrder(CreateOrderRequest request) {
        return null;
    }

    private boolean saveGroupBuyUserRelInfo(CreateOrderRequest request, Integer userId, String orderNo) {
        boolean result = false;
        if (null != request.getGroupBuyType()) {
            //记录团成员
            GroupBuyUserRel groupBuyUserRel = new GroupBuyUserRel();
            groupBuyUserRel.setGroupId(request.getGroupBuyId());//因为这时候还没有成团，所以是null，到时候支付成功后需要创建开团信息，并且回写这个字段
            groupBuyUserRel.setUserId(userId);
            groupBuyUserRel.setGroupRole(request.getGroupBuyType().byteValue());
            groupBuyUserRel.setVirtualUser((byte)0);
            groupBuyUserRel.setCreateTime(new Date());
            groupBuyUserRel.setWinFlag(0);
            groupBuyUserRel.setRedFlag(0);
            groupBuyUserRel.setStatus(0);
            groupBuyUserRel.setOrderNo(orderNo);
            groupBuyUserRel.setHeadImg(request.getHeadImg());
            groupBuyUserRel.setUserName(request.getNickName());
            result = yxGroupBuyUserRelService.insert(groupBuyUserRel);
        }
        log.info("===create order save yx_group_buy_user_rel result==={}", result);
        return result;
    }

    /**
     * 校验团剩余名额是否充足
     * @param groupBuyId
     * @return
     */
    private boolean checkGroupBuySurplusPerson(Integer groupBuyId, Integer userId) {
        log.info("===groupId==={}", groupBuyId);
        if (null == groupBuyId) {//表示非参团，而是开团
            return true;
        }
        GroupBuyInfo groupBuyInfo = yxGroupBuyInfoService.selectById(groupBuyId);//开团表
        if (null == groupBuyInfo) {
            throw new ApiException("找不到拼团信息");
        }
        if (groupBuyInfo.getFinalResult().equals(1)) {
            throw new ApiException("团已满，请重新开团或参团");
        }
        GroupBuyUserRelExample example = new GroupBuyUserRelExample();
        example.createCriteria().andGroupIdEqualTo(groupBuyId).andUserIdEqualTo(userId);
        List<GroupBuyUserRel> haveSelfOrder = groupBuyUserRelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(haveSelfOrder)) {
            throw new ApiException("您已加入该团，不能重复参团");
        }
        ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(groupBuyInfo.getProductId());//团配置表
        if (null == productGroupBuyInfo || productGroupBuyInfo.getStatus() != 1) {
            throw new ApiException("商品拼团已下架，请重新选择商品");
        }
        GroupBuyUserRelExample groupBuyUserRelExample = new GroupBuyUserRelExample();
        groupBuyUserRelExample.createCriteria().andGroupIdEqualTo(groupBuyId);//.andStatusEqualTo(1).andVirtualUserEqualTo((byte)0)
        List<GroupBuyUserRel> buyPersonNum = groupBuyUserRelMapper.selectByExample(groupBuyUserRelExample);
        if (buyPersonNum.size() >= productGroupBuyInfo.getMinPerson()) {
            throw new ApiException("团已满，请重新开团或参团");
        }
        return true;
    }
}
